package edu.yuhf.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.yuhf.domain.Page;
import edu.yuhf.domain.User;
import edu.yuhf.domain.UserDetail;
import edu.yuhf.service.iface.PermissionService;
import edu.yuhf.service.iface.UserService;
import edu.yuhf.web.dto.UserForm;

@Controller
public class UserController {
	
	@Resource
	UserService userService;
	@Resource
	PermissionService permissionService;

	@RequestMapping("/userInit")
	public ModelAndView init(@RequestParam(name="currentPage",defaultValue="1") String currentPage,
			@RequestParam(name="keyword",defaultValue="")String keyword) {
		Page<UserForm> page=new Page<>();
		page.setCurrentPage(Integer.valueOf(currentPage));
		ModelAndView mav=new ModelAndView("views/userManager");
		userService.showUserForPage(page, keyword);;
		mav.addObject("page",page);
		return mav;
	}
	
	@RequestMapping("/userLogin")
	public ModelAndView userNameCheck(@RequestParam(name="userName",defaultValue="") String name,@RequestParam String password,HttpServletRequest request) {
		ModelAndView mav=new ModelAndView("login");
		if(userService.checkUser(name, password)) {
			request.getSession().setAttribute("user", name);
			mav.addObject("permissions",permissionService.showPermission());
			mav.setViewName("views/main");
		}else {
			mav.addObject("message", "用户名或密码错误！");
		}
		return mav;
		
	}
	
	@RequestMapping("/userReg")
	public ModelAndView register(HttpServletRequest request) {
		String userName=null==request.getParameter("userName")?"":request.getParameter("userName");
		String password=null==request.getParameter("password")?"":request.getParameter("password");
		String sex=null==request.getParameter("sex")?"":request.getParameter("sex");
		String city=null==request.getParameter("city")?"":request.getParameter("city");
		String email=null==request.getParameter("email")?"":request.getParameter("email");
		String[] hobby=null==request.getParameterValues("hobby")?new String[] {}:request.getParameterValues("hobby");
		
		ModelAndView mav=new ModelAndView("login");
		
		String hobbyString="";
		if(hobby.length!=0) {
			for(int i=0,len=hobby.length;i<len;i++) {
				if(!hobbyString.equals("")) {
					hobbyString+=",";
				}
				hobbyString+=hobby[i];
			}
		}
		User user=new User(0,userName,password,sex,email);
		UserDetail ud=new UserDetail(0,city,hobbyString);
		
		if(userService.addUser(user, ud)) {
			mav.addObject("result", "success");
			mav.addObject("message", "用户注册成功！");
		}else {
			mav.addObject("result", "error");
			mav.addObject("message","用户注册失败！");
		}
		return mav;
	}
}
